package com.webchat.aigc.llm;


import com.webchat.common.helper.SseEmitterHelper;
import com.webchat.common.util.JsonUtil;
import com.webchat.domain.vo.llm.image.ImageGenerateResponse;
import com.webchat.domain.vo.llm.image.RequestGenerateBaseParam;
import com.webchat.domain.vo.llm.image.RequestGenerateParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Slf4j
@Service
public class AiGenImageService {

    @Autowired
    private LibLibGenerateImageService libLibGenerateImageService;

    /**
     * 旗舰版文生图模版id
     */
    private static final String TEMPLATE_UUID = "5d7e67009b344550bc1aa6ccbfa1d7f4";

    public String doGenerate(String message, String bizCode, String senderId) {
        // 机器人对话
        RequestGenerateBaseParam baseParam = RequestGenerateBaseParam.of(message);
        RequestGenerateParam param = RequestGenerateParam.of(TEMPLATE_UUID, baseParam);
        try {
            ImageGenerateResponse response = libLibGenerateImageService.generate(senderId, param);
            List<String> images = response.getImages();
            if (CollectionUtils.isEmpty(images)) {
                SseEmitterHelper.send(bizCode, senderId, "图片生成失败～");
                return null;
            }
            String imageMd = "<img src='%s'>";
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < images.size(); i++) {
                stringBuilder.append(String.format(imageMd, images.get(i)));
                if (i == images.size() - 1) {
                    stringBuilder.append("\n");
                }
            }
            String agentResponse = stringBuilder.toString();
            SseEmitterHelper.send(bizCode, senderId, agentResponse);
            return agentResponse;
        } catch (Exception e) {
            log.error("文生图服务异常 =====> param: {}", JsonUtil.toJsonString(param), e);
            SseEmitterHelper.send(bizCode, senderId, "意图识别失败，稍后重试～");
        }
        return null;
    }
}
